#include "fs.h"
#include "param.h"
#include "vnode.h"
#include <minix/vfsif.h>
#include <stdio.h>

/*===========================================================================*
 *                              do_nfrags                                    *
 *===========================================================================*/
PUBLIC int do_nfrags()
{
  struct vnode * vn;
  int r, n;

  /* Read message to get the vnode */
  if( (r = frag_get_vnode(&vn)) != 0 )
      return(r);

  /* Request the FS for nfrags: */
  if((r = req_nfrags(vn->v_fs_e, vn->v_inode_nr, vn->v_dev, &n)) != OK)
      return(EGENERIC); /* This generally shouldn't happen */

  put_vnode(vn);
  return( n );
}

/*===========================================================================*
 *                              frag_get_vnode                               *
 *===========================================================================*/
PUBLIC int frag_get_vnode(struct vnode ** ret) 
{
/* Generic function to get the vnode for nfrags and defrag.
 * Checks conditions. Return negative value if an error occurs.
 * The vnode is returned through the parameter ret. 
 */
#define error(e) put_vnode(vn); return(e);

  struct vnode * vn;
  int error;
  
  /* Get file name  */
  if (fetch_name(m_in.name, m_in.name_length, M3) != OK) {return(err_code);}

  /* Get vnode */
  if ((vn = eat_path (PATH_NOFLAGS, fp)) == NULL) {return(err_code);}

  /* Check filetype: */
  if      (vn->v_mode & I_DIRECTORY)     {error(EISDIR);}
  else if (vn->v_mode & I_BLOCK_SPECIAL) {error(EFTYPE);}

  /* Check in-use: */
  if( vn->v_ref_count != 1 ) {
      error(EBUSY);
  }

  * ret = vn;

  return(0);
}
